<template>
  <div>
    <el-card class="box-card">
      <!--头部-->
      <template #header>
        <div class="card-header">
          <div class="cardsize">
            <h2 style="font-size: 18px; font-weight: bold">志愿填报</h2>
            <!-- <div style="font-size: 15px">共 {{ pageData.total ?? 0 }} 单</div> -->
            <!-- <div style="font-size: 15px">
              已处理 {{ totalCount.orderStatus_1 }} 单
            </div>
            <div style="font-size: 15px">
              已审核 {{ totalCount.orderStatus_2 }} 单
            </div>
            <div style="font-size: 15px">
              已完成 {{ totalCount.orderStatus_3 }} 单
            </div> -->
          </div>
        </div>
      </template>
      <!--列表数据-->
      <el-row :gutter="20">
        <el-col :span="5">
          <el-input
            v-model="pageData.search"
            placeholder="考生/考生/手机号"
            clearable
            @clear="searchChange"
          >
            <template #append>
              <el-button
                type="primary"
                style="height: 40px"
                @click="searchChange"
                >搜索</el-button
              >
            </template>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-select
            v-model="pageData.pid"
            class="m-2"
            placeholder="省份"
            size="large"
            clearable
            @change="searchChange"
          >
            <el-option
              v-for="item in provincelist"
              :key="item.id"
              :label="item.provinceName"
              :value="item.id"
            />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-select
            v-model="pageData.graduate_time"
            class="m-2"
            placeholder="高考年份"
            size="large"
            clearable
            @change="searchChange"
          >
            <el-option
              v-for="item in gaokaoyear"
              :key="item.val"
              :label="item.name"
              :value="item.val"
            />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-select
            v-model="pageData.orderStatus"
            class="m-2"
            placeholder="状态"
            size="large"
            clearable
            @change="searchChange"
          >
            <el-option
              v-for="item in statuslist"
              :key="item.val"
              :label="item.name"
              :value="item.val"
            />
          </el-select>
        </el-col>
        <el-col :span="10" style="display: flex; justify-content: flex-end">
          <el-button
            style="height: 40px"
            @click="onClickBatchDistribution"
            v-hasPermi="['leader:filling:add']"
            >批量分配</el-button
          >
          <!-- <el-button
            :icon="Bottom"
            style="height: 40px"
            @click="onClickOrdersExport"
            v-hasPermi="['leader:filling:download']"
            >下载</el-button
          >
          <el-button
            type="primary"
            :icon="Plus"
            style="height: 40px"
            @click="addUserOrder"
            v-hasPermi="['leader:filling:addkd']"
            >创建客单</el-button
          > -->
        </el-col>
      </el-row>
      <el-divider />
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        v-loading="isRequest"
        @selection-change="handleSelectionChange"
        :row-class-name="tableRowClassName"
      >
        <!-- <el-table-column>
         <template #default="scope"> 
          {{ scope.row.status }}
         </template>
        </el-table-column> -->
        <el-table-column
            type="selection"
            width="30"
            :selectable="isRowSelectable"
            /> 
        <el-table-column
          prop="province"
          label="省份"
          align="center"
          width="70"
        >
        </el-table-column>
        <!-- <el-table-column prop="nick" label="姓名" align="center">
          <template #default="scope">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="scope.row.gkaProvinceName"
              placement="top"
            >
              <div
                v-if="!scope.row.nick"
                style="color: #165dff; cursor: pointer"
                :class="{
                  isPassed: scope.row.passed,
                }"
              >
                {{ scope.row.nick }}
              </div>
              <div
                v-else
                style="color: #165dff; cursor: pointer"
                :class="{
                  isPassed: scope.row.passed,
                }"
                @click="lookUserInfo(scope.row)"
              >
                {{ scope.row.nick }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="nick"
          label="姓名"
          align="center"
          width="110"
        >
        <template #default="scope">
          <span @click="lookUserInfo(scope.row)" style="color: blue;">
            {{ scope.row.nick }}
          </span> 
        </template>
        </el-table-column>
        <el-table-column
          prop="student.sex"
          label="性别"
          align="center"
          width="50"
        >
          <template #default="scope">
            <div>{{ scope.row.sex == 0 ? '男' : '女' }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="phone"
          label="手机号"
          width="110"
          align="center"
        />
        <el-table-column
          prop="graduate_time"
          label="高考年份"
          width="80"
          align="center"
        />
        <el-table-column prop="grade" label="成绩" width="220" align="center">
          <!-- <template #default="scope">
            <div v-if="!!scope.row.student">
              <div
                v-if="
                  scope.row.isGKB == 1 && scope.row.student.gkb_score_num == 0
                "
                @click="lookGradeChange(scope.row)"
                style="color: rgb(22, 93, 255)"
              >
                请创建高考成绩
              </div>
              <div
                v-else-if="
                  scope.row.isGKB == 1 && scope.row.student.gkb_score_num == 1
                "
              >
                {{
                  scope.row.student
                    ? scope.row.student.score +
                      '分 ' +
                      scope.row.student.section +
                      '位 ' +
                      scope.row.student.sgname
                    : ''
                }}
              </div>
              <div v-else>
                {{
                  scope.row.student
                    ? scope.row.student.score +
                      '分 ' +
                      scope.row.student.section +
                      '位 ' +
                      scope.row.student.sgname
                    : ''
                }}
                <el-icon
                  size="18"
                  @click="lookGradeChange(scope.row)"
                  style="cursor: pointer"
                >
                  <EditPen />
                </el-icon>
              </div>
            </div>
          </template> -->
          <template #default="scope">
            <div>
              {{ scope.row.score}} {{ scope.row.sgname }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="teacher" label="老师" width="130" align="center">
          <template #default="scope">
            <div>
              <el-dropdown trigger="click" :disabled="scope.row.passed == 1">
                <span
                  :class="
                    scope.row.passed == 1 ? 'isPassed' : 'el-dropdown-link'
                  "
                >
                  {{ scope.row.teacherName }}
                  <el-icon
                    class="el-icon--right"
                    v-hasPermi="['leader:filling:add']"
                  >
                    <arrow-down />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu
                    v-hasPermi="['leader:filling:add']"
                    style="
                      max-height: 400px;
                      overflow: hidden;
                      overflow-y: auto;
                      padding: 10px;
                    "
                  >
                    <el-select-v2
                      filterable
                      model-value=""
                      :options="teacherArr"
                      :props="{
                        label: 'realName',
                        value: 'id',
                      }"
                      value-key="id"
                      placeholder="请选择老师"
                      style="width: 240px"
                      @change="
                        (selectedValue) => onChangeFilter(scope, selectedValue)
                      "
                    />
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="creationTime"
          label="创建时间"
          width="160"
          align="center"
        >
          <template #default="scope">
            <div>{{ scope.row.addTime }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="history"
          label="历史提交"
          width="250"
          align="center"
        >
          <template #default="scope">
            <div>
              <el-button @click="viewHistory(scope.row)">
                点击查看
              </el-button>
              提交次数：{{ scope.row.count }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <div>{{ getStatusText(scope.row.status) }}</div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center">
          <template #default="scope">
            <el-button @click="ViewDetails(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 20px"
        :current-page="pageData.page"
        :page-size="pageData.pageSize"
        v-if="pageData.total"
        :page-sizes="[10, 20, 30, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 批量分配 -->
    <batchDistribution
      ref="batchDistributionRef"
      :teacherArr="teacherArr"
      :selStudentArr="selStudentArr"
      @refreshList="pagination"
    >
    </batchDistribution>
    <!-- 添加用户 -->
    <!--用户修改信息-->
     <userUpdate
      ref="userUpdatesRef"
      @refreshStudentList="pagination"
      @getTzyCount="getTzyCount"
    ></userUpdate>
    <!--填报-->
  </div>
  <!-- 点击名字的弹窗 -->
  <el-dialog v-model="dialogFormVisible" title="基础信息">
    <el-form :inline="true" :model="NameDataList" class="demo-form-inline">
      <el-form-item label="姓名:" :label-width="formLabelWidth">
        <span>
          {{ NameDataList.nick }}
        </span>
      </el-form-item>
      <el-form-item label="考生性别：" :label-width="formLabelWidth">
        <span>
          {{ NameDataList.sex==1?'男':'女' }}
        </span>
      </el-form-item>
      <el-form-item label="考生民族：" :label-width="formLabelWidth">
        <span>
          {{ NameDataList.sex==1?'男':'女' }}
        </span>
      </el-form-item>
      <el-form-item label="登录账号：" :label-width="formLabelWidth">
        <span>
          {{ NameDataList.phone }}
        </span>
      </el-form-item>
      <el-form-item label="高考省份：" :label-width="formLabelWidth">
        <span>
          {{ NameDataList.province }}
        </span>
      </el-form-item>
      <el-form-item label="高考年份：" :label-width="formLabelWidth">
        <span>
          {{ NameDataList.graduate_time }}
        </span>
      </el-form-item>
      <el-form-item label="学校地区：" :label-width="formLabelWidth">
        <span>
          {{ NameDataList.province }}
        </span>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 点击查看查看历史 -->
  <el-dialog v-model="HistoricalSubmission" title="历史记录">
    <div>
      <div class="HistoricalNum">
        提交次数：{{FromDataListNum}}
      </div>
      <el-table :data="FromDataList" style="width: 100%">
        <el-table-column type="expand">
          <template #default="props">
            <div m="4">
              <el-table :data="props.row.familys" :border="true">
                <el-table-column label="创建时间" prop="addTime" />
                <!-- <el-table-column label="成绩" prop="family" />
                <el-table-column label="表名" prop="title" /> -->
                <el-table-column label="备注" prop="remark" />
                <el-table-column label="完成时间" prop="saveTime" />
                <el-table-column property="status" label="状态" >
                  <template #default="scope">
                    {{ getStatusText(scope.row.status) }}
                  </template>
                </el-table-column>
                <el-table-column property="status" label="操作" >
                  <template #default="scope">
                    <el-button @click="queryData(scope.row)">查看</el-button>
                  </template>
                </el-table-column>
                
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="表名" property="title" />
        <!-- <el-table-column label="创建时间" property="addTime" />
        <el-table-column property="remark" label="备注" width="200" /> -->
        <el-table-column property="family" label="成绩"  />
        <el-table-column property="status" label="状态" >
          <template #default="scope">
            {{ getStatusText(scope.row.status) }}
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="HistoricalSubmission=false">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import batchDistribution from './module/batchDistribution.vue';
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
// import { omit } from 'lodash';
import userUpdate from './module/userUpdate.vue';
const route = useRoute();
import {
  SubscriberList,
  getProvince,
  tzyOrdersCount,
  // tzyOrdersCreate,
  SubmitHistory,// 提交历史
  tzyOrdersListFilter,
} from '@/api/leader/Filling.js';
import { getProvinceList,Approved } from '@/api/appv2/appv2'; // 省份
import bus from '@/utils/bus.js';
import { accountListExpserts } from '@/api/system/account.js';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
const formLabelWidth = '140px'
const FromDataList = ref([]);// 保存历史提交记录
const FromDataListNum = ref(null);
const batchDistributionRef = ref(null);
const addUserInfoRef = ref(null);
const HistoricalSubmission = ref(false); // 提交历史
const dialogFormVisible = ref(false); // 点击名字打开弹窗的状态
const userUpdatesRef = ref(null);
const router = useRouter()
const tableData = ref([]);
const studentId = ref()  // 学生id
const pid = ref() // pid传入
const score = ref() // 成绩
// const zyId = ref(); // 查看历史提交
const pageData = ref({
  page: 1,
  pageSize: 10,
  total: 0,
  search: '',
});
// function mergeAllArrays(data) { // 整合数据
//   return Object.values(data).flat();
// }
const viewHistory = (row) => { // 点击查看历史
  console.log(row,"hhhhhhhj");
  score.value = row.score
  studentId.value = row.studentId
  pid.value = row.pid
  FromDataListNum.value = row.count
  HistoricalSubmission.value = true
  SubmitHistory({
    phone:row.phone,
    id:row.zyId
  }).then((res)=>{
    // const list = res.data
    FromDataList.value = res.data
    // 为了给数组里面对象里面的数组的第一个对象的状态进行填充到数组第一层的每个对象属性中
    FromDataList.value.forEach(item => {
      if (item.familys && item.familys.length > 0) {
        // 获取familys数组第一个对象的status属性
        const status = item.familys[0].status;
        // 将status添加到当前对象
        item.status = status;
      }
    });
    // console.log(FromDataList.value,"hgggggggjgjh");
    // 获取提交的次数
    //     FromDataListNum.value += list[key].length;
 
  })
}
const provinceList = ref([]);
const totalCount = ref({});
const provincelist = ref([]); // 省份
const gaokaoyear = ref([]); // 高考年份
const statuslist = ref([]); // 查询状态
const isRequest = ref(false);
const teacherArr = ref([]); // 老师数组
const selStudentArr = ref([]); // 选中学生数组
const NameDataList = ref()
bus.on('refreshList', () => {
  pageData.value.page = 1;
  pagination();
});
const getStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '审核中',
    2: '驳回',
    3: '成功',
    4: '撤回',
  };
  return statusMap[status] || '未知状态';
};
// 点击查看
const ViewDetails = (row)=>{
  const body = btoa(encodeURIComponent(JSON.stringify(row)));
//  const encodedBody = btoa(encodeURIComponent(body)); // 先进行 URL 编码，再进行 Base64 编码
  router.push({
    path: '/leader/ExamineComponent',
    query: {
      TypeQuery:"1",
      data: body
    },
  });
}
const queryData = (row)=>{
  row.studentId = studentId.value
  row.pid = pid.value
  row.score = score.value
  console.log(row,"jhjgdgggg111111111");
  const body = btoa(encodeURIComponent(JSON.stringify(row)));
//  const encodedBody = btoa(encodeURIComponent(body)); // 先进行 URL 编码，再进行 Base64 编码
  router.push({
    path: '/leader/ExamineComponent',
    query: {
      TypeQuery:"1",
      data: body
    },
  });
}
// 查看数据表里面的查看
// const queryData = (val) =>{
//   console.log(val);
  
// }
// 切换大小
const handleSizeChange = (val) => {
  pageData.value.pageSize = val;
  pagination();
};
// 切换页码
const handleCurrentChange = (val) => {
  pageData.value.page = val;
  pagination();
};
const fetchProvince = () => {
  getProvinceList().then((res) => {
    provincelist.value = res.data;
  });
};
fetchProvince();
function searchDate() {
  tzyOrdersListFilter().then((res) => {
    // provincelist.value = res.data[0].data;
    gaokaoyear.value = res.data[1].data;
    // statuslist.value = res.data[2].data;
    console.log(statuslist.value);
    statuslist.value = [
      { val: 0, name:'待审核' },
      { val: 1, name:'审核中' },
      { val: 2, name:'驳回' },
      { val: 3, name:'成功' },
      { val: 4, name:'撤回' },
    ]
  });
  // statuslist.value = [0,1,2,3,4]
}
searchDate();

function getTzyCount() {
  tzyOrdersCount().then((res) => {
    totalCount.value = res.data;
  });
}
getTzyCount();

function searchChange() {
  // 添加查询参数
  pageData.value.page = 1;
  pagination();
}

function pagination() {
  // pageData.value.page = page
  // 分页加载请求数据
  if (isRequest.value) return;
  isRequest.value = true;

  let data = pageData.value;
  Object.keys(data).forEach((key) => {
    // 检查值是否为数组、字符串并且长度为0，或值为 undefined
    if (
      (Array.isArray(data[key]) && data[key].length === 0) ||
      data[key] === undefined ||
      data[key] === null
    ) {
      delete data[key];
    }
  });
  SubscriberList(data) // 审核列表
    .then((res) => {    
      // console.log(res,"审核列表数据");
      isRequest.value = false;
      tableData.value = res.data.data;
      // console.log(tableData.value,"tableData.value");
      pageData.value.page = res.data.current_page;
      pageData.value.total = res.data.total;
    })
    .catch(() => {
      isRequest.value = false;
    });
}
pagination();

// 检测每一行是否能被选中
const isRowSelectable = (row) => {
  // 可以根据行的某些条件判断是否禁用
  return row.status != 3;
};

// 置灰
const tableRowClassName = ({ row }) => {
  if (row.passed === 1) {
    return 'ashes';
  }
  return '';
};
getAccountList();
// 获取老师列表
function getAccountList() {
  accountListExpserts({
    pageSize: 999,
    TypeTeacher:1
  }).then((res) => {
    teacherArr.value = res.data.data; 
  });
}

// 学生勾选数据改变
function handleSelectionChange(val) {
  selStudentArr.value = val;
}

const onChangeFilter = (scope, teacherId) => {
  Approved({
    id:scope.row.id,
    teacherId:teacherId
  }).then((res)=>{
    console.log(res);
    pagination()
  })
  // const teacher = teacherArr.value.find(
  //   (item) => item.id === teacherId
  // )?.realName;
  // let data = { id: scope.row.id, teacherId, teacher };

  // // 更新用户信息
  // tzyOrdersCreate(data).then(() => {
  //   tableData.value[index].teacherId = teacherId;
  //   tableData.value[index].teacher = teacher;
  //   // 更新表单数量
  //   getTzyCount();
  // });
};
// 批量分配
function onClickBatchDistribution() {
  if (selStudentArr.value.length == 0) {
    ElMessage({
      message: '请选择需要分配的学生',
      type: 'warning',
    });
    return;
  }
  batchDistributionRef.value.openChange();
}


// 用户详情
function lookUserInfo(val) {
 
  NameDataList.value = val
  // console.log(NameDataList.value,"hhghhhhh");
  dialogFormVisible.value = true
}

// function lookGradeChange(val) {
//   if (val.passed) return;
//   userUpdatesRef.value.openChange(val);
// }

const provinceDataList = async () => {
  getProvince().then((res) => {
    provinceList.value = res.data;
    localStorage.setItem(
      'provinceDataList',
      JSON.stringify(provinceList.value)
    );
  });
};
provinceDataList();
onMounted(() => {
  if (route.query.dialog == 'true') {
    addUserInfoRef.value.showAddUserInfo();
  }
});
</script>
<style lang="scss" scoped>
.HistoricalNum{
  font-weight: bold;
  font-size: 17px;
  color: black;
  text-align: center;
  padding: 10px 0;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
@import '@/assets/styles/global.scss';
:deep(.el-dialog) {
  max-height: none !important;
}
.eva {
  cursor: pointer;
}

.zyb-count {
  background: #fff;
  border-radius: 4px 4px 4px 4px;
  opacity: 1;
  border: 1px solid #165dff;
  padding: 5px 10px;
  font-size: 14px;
  font-family:
    PingFang SC-Regular,
    PingFang SC;
  font-weight: 400;
  line-height: 14px;
  display: flex;
  justify-content: space-between;
  color: #165dff;
}
.zyb-count-isPassed {
  border: 1px solid #cdcdcd;
  color: #cdcdcd;
}

.box-card {
  margin: 20px;
  .cardsize {
    display: flex;
    align-items: center;
    font-weight: 400;

    div {
      margin-left: 20px;
    }
  }
}
:deep(.el-table .ashes) {
  color: #cdcdcd !important;
}
.isPassed {
  color: #cdcdcd !important;
}
</style>
